<template>
  <div>
    <!-- 卡片 -->
    <el-card>
      <div style="font-size:20px;margin-bottom:20px;">监控管理</div>
      <el-row :gutter="20">
        <el-col :span="3.5">
          <el-select v-model="projectN" placeholder="请选择项目" @change="getList(1)" filterable>
            <el-option label="全部" value=""></el-option>
            <el-option
              v-for="item in projOptions"
              :key="item.pid"
              :label="item.project_name"
              :value="item.project_name">
            </el-option>
            
          </el-select>
        </el-col>
        <!-- <el-col :span="8">
          <el-input placeholder="请输入监测点名称、项目名称" size="small" v-model="name" clearable>
            <el-button slot="append" icon="el-icon-search" @click="getList(1)">搜索</el-button>
          </el-input>
        </el-col> -->
        <a></a>
        <el-col :span="12.5" style="float: right;">
          <el-upload
            style="display: inline-block;margin-right: 20px;"
            :action="upload"
            accept=".xls, .xlsx"
            :show-file-list="false"
            :headers="headers"
            multiple
            name="excel"
            :limit="1"
            :on-success="handleAvatarSuccess"
            :file-list="fileList">
            <el-button size="small" type="primary">上传Excel</el-button>
          </el-upload>
          
          <el-button @click="downLoadFn" size="small" >下载模板  </el-button>
          <el-button @click="look" size="small" >视频墙</el-button>
          <!-- <el-button @click="add" size="small">添加监控</el-button> -->
          <el-button @click="add" size="small" v-if="role!='SUPER'">添加监控</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="tableData" stripe style="width: 100%">
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="name" label="监测点名称" min-width="120" show-overflow-tooltip></el-table-column>
        <el-table-column prop="deviceSerial" label="设备号" min-width="60" show-overflow-tooltip></el-table-column>
        <el-table-column prop="channelNo" label="通道号" min-width="30" show-overflow-tooltip></el-table-column>
        <el-table-column prop="projectName" label="项目名称" min-width="160" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="toDetail(scope.row)">{{scope.row.projectName}}</el-button>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="address" label="安装位置" show-overflow-tooltip></el-table-column> -->
        <el-table-column label="操作" width="120px">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button type="text" size="mini" @click="update(scope.row)" v-if="role!='SUPER'">编辑</el-button>
            <!-- <el-button type="text" size="mini" @click="update(scope.row)" >编辑</el-button> -->
            <!-- 查看按钮 -->
            <el-button type="text" size="mini" @click="detail(scope.row)">查看</el-button>
            <el-button type="text" size="mini" @click="deleteItem(scope.row.id)" v-if="role!='SUPER'">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
        :page-sizes="[10, 20, 30, 100]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
        :total="total"></el-pagination>
    </el-card>
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form :label-position="labelPosition" ref="form" :model="form" :rules="rules" label-width="100px" size="small"
        style="width:380px;margin: 0 auto;">
        <div>
          <el-form-item label="监测点名称" prop="name">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="监控类型" prop="monitorType">
            <!-- <el-input v-model="form.monitorType"></el-input> -->
            <el-radio-group v-model="form.monitorType">
              <el-radio :label="1">海康</el-radio>
              <el-radio :label="2">大华</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="所属项目" prop="pid">
            <el-select v-model="form.pid" placeholder="请选择所属项目" style="width:280px;" filterable>
              <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="RTMP地址" prop="rtmp">
            <el-input v-model="form.rtmp"></el-input>
          </el-form-item>
          <el-form-item label="HLS地址" prop="url">
            <el-input v-model="form.url"></el-input>
          </el-form-item>
          <el-form-item label="安装地址" prop="address">
            <el-input v-model="form.address"></el-input>
          </el-form-item>
          <el-form-item label="设备号" prop="deviceSerial">
            <el-input v-model="form.deviceSerial"></el-input>
          </el-form-item>
          <el-form-item label="通道号" prop="channelNo">
            <el-input v-model="form.channelNo"></el-input>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer botton_btn">
        <el-button type="primary" @click="save" size="small" style="margin-right:40px;">保 存</el-button>
        <el-button @click="cancel" size="small">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 查看详情 -->
    <el-dialog title="查看监控" :visible.sync="dialogVisible">
      
        <!-- <el-button @click="go" icon="el-icon-back" type="text">返回</el-button> -->
           <!-- <vue-aliplayer-v2 :source="src" autoplay ref="VueAliplayerV2" id="player-1194076936807170050" :options="options"/> -->
          <iframe
            v-if='succ'
            :src="url"
            width="100%"
            height="650"
            id="ysOpenDevice"
            allowfullscreen
          >
          </iframe>
          <!-- <div v-if="monitorType == 2" id="lc"></div> -->
          <div id="lc" v-if="!succ"></div>
    </el-dialog>
  </div>
</template>

<script>
  import base from "../api/base"
  import axios from 'axios'
  export default {
    data() {
      return {
        fileList:[],
        upload: base.uploadExcel,
        downloadExcel: base.uploadExcel,
        headers:{token:localStorage.getItem('token')},
        role:localStorage.getItem('role'),
        name: "",
        succ:true,
        url:'',
        tableData: [],
        projOptions:[],
        //   分页
        currentPage: 1,
        pageSize: 10,
        total: 0,
        projectN:'',
        dialogFormVisible: false, // 弹框是否显示
        dialogVisible:false,
        title: "添加监控",
        labelPosition: "left", // 表单标签文字位置
        form: {
          name: "",
          monitorType: "",
          address: "",
          rtmp: "",
          url: "",
          pid: "",
          channelNo: "",
          deviceSerial: "",
        },
        id: "",
        options: [],
        rules: {
          name: [{
            required: true,
            message: "请输入监测点名称",
            trigger: "blur"
          }],
          pid: [{ required: true, message: '请选择所属项目', trigger: 'change' }],
          monitorType: [{
            required: true,
            message: "请选择监控类型",
            trigger: "blur"
          }],
          deviceSerial:[{
            required: true,
            message: "请输入设备号",
            trigger: "blur"
          }],
          channelNo:[{
            required: true,
            message: "请输入通道号",
            trigger: "blur"
          }],
        },
      };
    },
    methods: {
      //上传
      handleAvatarSuccess(res, file){
        if(res.code==200){
          this.$message.success("上传成功");
        }
      },
      downLoadFn(){
        axios({
            method:'get',//请求方式
            url:base.downloadExcel,
            headers:{token:localStorage.getItem('token')},
            responseType:'blob'//服务器返回的数据类型
        }).then(response=>{
            const content = response.data //返回的内容
            const fileName = '模板.xls'//下载文件名
            const blob = new Blob([content]) //创建一个类文件对象：Blob对象表示一个不可变的、原始数据的类文件对象
            const url = window.URL.createObjectURL(blob)//URL.createObjectURL(object)表示生成一个File对象或Blob对象
            let dom = document.createElement('a')//设置一个隐藏的a标签，href为输出流，设置download
            dom.style.display = 'none'
            dom.href = url
            dom.setAttribute('download',fileName)//指示浏览器下载url,而不是导航到它；因此将提示用户将其保存为本地文件
            document.body.appendChild(dom)
            dom.click()
        })
      },
      toDetail(row){
        console.log(row)
        let token = window.localStorage.getItem("token")
      window.location.href = `${base.spurl}/ncpr-lv/index?id=${row.pid}&token=${token}&path=videoManagement`
      },
      look(){
        let token  = window.localStorage.getItem("token")
        window.location.href = `${base.spurl}/ncpr-lv/monitor?token=${token}&path=videoManagement`
      },
      errFn(S,N,P){
          // 重新获取token
      //   getLcToken
      this.$api.loginhome.getLcToken({
        pid: P,
        monitorType: 2,
        channelId: N,
        deviceId: S
      }).then((res) => {
        // console.log("res.token", res.data)
        // 初始化乐橙
        const player = new ImouPlayer('#lc');
        player.setup({
          src: [{
            url: `imou://open.lechange.com/${S}/${N}/1?streamId=1`, // url拼接说明请见：2.2.3 轻应用播放地址说明
            kitToken: res.data, // 播放Token，通过接口getKitToken获取，具体请见：2.2.4 getKitToken接口协议说明
          }], // 播放地址
          width: "100%", // 播放器宽度
          height: 650, // 播放器高度
          poster: '', // 封面图url
          autoplay: true, // 是否自动播放
          controls: true, // 是否展示控制栏
        });
        // 播放
        player.play();
      })
      },
      //查询所有项目
      find() {
        this.$api.loginhome.findAllNcpr().then((res) => {
          if (res.success) {
            this.options = res.data;
          }
        });
      },
      //分页
      handleSizeChange(val) {
        this.pageSize = val;
        this.getList();
      },
      handleCurrentChange(val) {
        this.currentPage = val;
        this.getList();
      },
      // 删除
      deleteItem(row) {
        this.$confirm("此操作将删除监控, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          this.$api.loginhome.deleteMonitor({
            id: row
          }).then((res) => {
            if (res.success) {
              this.$message.success("删除成功");
              this.getList();
            } else {
              this.$message.error(res.message);
            }
          });
        });
      },
      //新增
      add() {
        this.form = {
          name: "",
          monitorType: "",
          address: "",
          rtmp: "",
          url: "",
          pid: "",
          channelNo: "",
          deviceSerial: "",
        }
        this.dialogFormVisible = true;
        this.title = "添加监控";
        this.$refs["form"].resetFields();
      },
      cancel() {
        this.dialogFormVisible = false;
        this.$refs["form"].resetFields();
      },
      //保存新增
      save() {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            if (this.title === "添加监控") {
              this.$api.loginhome.save(this.form).then((res) => {
                if (res.success) {
                  this.$message.success("添加监控成功");
                  this.dialogFormVisible = false;
                  this.$refs["form"].resetFields();
                  this.getList();
                } else {
                  this.$message.error(res.message);
                  this.getList();
                }
              });
            } else {
              this.$api.loginhome
                .update({
                  ...this.form,
                  id: this.id
                })
                .then((res) => {
                  if (res.success) {
                    this.$message.success("修改成功");
                    this.dialogFormVisible = false;
                    this.$refs["form"].resetFields();
                    this.getList();
                  } else {
                    this.$message.error(res.message);
                    this.getList();
                  }
                });
            }
          } else {
            return false;
          }
        });
      },
      // 修改跳转
      update(row) {
        this.form = row;
        this.dialogFormVisible = true;
        this.id = row.id;
        this.title = '修改监控'
      },
      //查看查看详情
      detail(row) {
        // console.log("row", row)
        this.$api.loginhome.tokenMonitor({
          pid: row.pid
        }).then((res) => {
          // console.log(res);
          this.dialogVisible = true
          if (row.monitorType == 1) {
            this.succ = true
            this.url = `https://open.ys7.com/ezopen/h5/iframe_se?url=ezopen://open.ys7.com/${row.deviceSerial}/${row.channelNo}.live&accessToken=${res.data}&templete=2`
            // this.$router.push({
            //   path: "/addVideo",
            //   query: {
            //     deviceSerial: row.deviceSerial,
            //     channelNo: row.channelNo,
            //     videoToken: res.data,
            //     monitorType: row.monitorType,
            //   },
            // });
          } else {
            this.succ = false
            this.errFn(row.deviceSerial,row.channelNo,row.pid)
            // this.$router.push({
            //   path: "/addVideoLc",
            //   query: {
            //     deviceSerial: row.deviceSerial,
            //     channelNo: row.channelNo,
            //     videoToken: res.data,
            //     monitorType: row.monitorType,
            //     pid: row.pid
            //   },
            // });
            // this.$message.error(res.message);
          }
        });
      },

      getOptions(){
        this.$api.loginhome.getProjOptions().then(res=>{
          if(res.success)
          this.projOptions = res.data
        })
      },
      //刷新列表
      getList(val) {
        if (val) {
          this.currentPage = 1;
        }
        let params = {
          name: this.projectN,
          start: this.currentPage - 1,
          pageSize: this.pageSize,
          // projectName:this.projectN
        };
        this.$api.loginhome
          .page(params)
          .then((res) => {
            this.tableData = res.data;
            this.total = res.recordsTotal;
            this.find();
          })
          .catch(() => {});
      },
    },
    created() {
      this.getList();
      this.getOptions()
    },
  };
</script>

<style scoped>
  .el-pagination {
    padding-top: 20px;
    text-align: right;
  }

  /deep/.el-table th,
  .el-table tr {
    background: #e4e4e4;
  }

  /deep/.el-table thead {
    color: #7a7c80;
  }

  /deep/.el-input-group__append button.el-button {
    background-color: #409eff;
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
    height: 32px;
  }

  /deep/.el-input-group__append .el-button {
    padding: 10px 20px;
  }

  /deep/.el-input-group__append,
  .el-input-group__prepend {
    color: #ffffff;
  }

  /deep/.el-table td,
  .el-table th {
    text-align: center;
  }

  /deep/.el-table th>.cell {
    text-align: center;
  }

  /deep/.el-col-16 {
    text-align: right;
  }

  /deep/.el-dialog__body {
    margin: -35px 0px;
  }

  .con_dialog h4 {
    margin: 7px 0px 7px 30px;
  }

  .con_dialog p {
    margin: 7px 0px 7px 60px;
    font-size: 12px;
  }

  .mapbox {
    width: 610px;
    height: 220px;
    background: gainsboro;
    margin: 10px 0px 7px 60px;
  }

  .time_span {
    text-align: right;
    padding: 10px 48px 10px 10px;
  }

  .botton_btn {
    display: flex;
    justify-content: center;
    padding-top: 20px;
  }

  /deep/.el-input__inner {
    height:32px;
  }
  /deep/.el-input__icon{
    line-height: 30px;
  }
</style>